<?php

namespace app\member\controller\sys_admin;

use app\AdminController;
use app\distribution\controller\sys_admin\LevelApply;
use app\member\model\UsersModel;
use app\member\model\UserAddressModel;
use app\member\model\UsersBindSuperiorModel;
use app\member\model\LogSysModel;
use app\distribution\model\DividendRoleModel;
use app\distribution\model\DividendModel;
use app\publics\controller\api\Areas;
use app\weixin\model\WeiXinUsersModel;
use app\member\model\UsersLevelAgentModel;
use app\member\model\UsersLevelModel;
use app\member\model\UsersLevelApplyModel;
use think\Db;
use think\facade\Cache;

/**
 * 会员管理
 * Class Index
 * @package app\store\controller
 */
class Users extends AdminController
{
    public $is_ban = 0;
    /*------------------------------------------------------ */
    //-- 优先执行
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->Model = new UsersModel();
    }
    /*------------------------------------------------------ */
    //-- 首页
    /*------------------------------------------------------ */
    public function index()
    {
        $this->assign('rode_id', input('rode_id', 0, 'intval'));
        $this->assign('additional_setapply', input('additional_setapply', 0, 'intval'));
        $this->assign("start_date", date('Y/m/01', strtotime("-1 months")));
        $this->assign("end_date", date('Y/m/d'));
        $this->getList(true);

        //首页跳转时间
        $start_date = input('start_time', '0', 'trim');
        $end_date = input('end_time', '0', 'trim');
        if ($start_date || $end_date) {

            $this->assign("start_date", str_replace('_', '/', $start_date));
            $this->assign("end_date", str_replace('_', '/', $end_date));
        }
        $this->assign("roleOpt", arrToSel($this->roleList, $this->search['roleId']));
        $this->assign("levelOpt", arrToSel($this->levelList, $this->search['levelId']));
        $jc_list = Db::name('users_level_apply')->where([])->select();
        $this->assign("jcOpt", $jc_list);
        return $this->fetch('sys_admin/users/index');
    }

    protected function ld_grade_name_lists(){
        $arr = [0=>'粉丝',1=>'服务中心',2=>'分公司',3=>'联创股东'];
        return $arr;
    }
    protected function ld_grade_name_list($ld_grade=0){
        $arr = [0=>'粉丝',1=>'服务中心',2=>'分公司',3=>'联创股东'];
         return $arr[$ld_grade];
    }
    public function editGrade()
    {
        $user_id = input('user_id', 0, 'intval');
        $row = $this->Model->info($user_id);
        $DividendRoleModel = new DividendRoleModel();
        $roleList = $this->ld_grade_name_lists();
        if ($this->request->isPost()) {
            $data['ld_grade'] = input('role_id', 0, 'intval');
            if($data['ld_grade']>0){
                $data['ld_grade'] -=1;
            }
            $this->checkUpData($row, $data);
            $res = $this->Model->upInfo($user_id, $data);
            if ($res < 1) return $this->error('操作失败,请重试.');
            $info = '后台手工操作由【' . ($this->ld_grade_name_list($row['ld_grade'])) . '】调整为【' .($this->ld_grade_name_list($data['ld_grade'])) . '】';
            $this->_log($user_id, $info, 'member');
            return $this->success('修改身份成功！', 'reload');
        }
        $this->assign("roleList", $roleList);
        $this->assign("row", $row);

        return $this->fetch('sys_admin/users/edit_ldgrade');
    }

    /*------------------------------------------------------ */
    //-- 获取列表
    //-- $runData boolean 是否返回模板
    /*------------------------------------------------------ */
    public function getList($runData = false, $is_ban = -1)
    {
        $this->search['roleId'] = input('rode_id', -1);
        $this->search['levelId'] = input('level_id', 0, 'intval');
        $this->search['keyword'] = input("keyword");
        $this->search['additional_setapply'] = input('additional_setapply', 0, 'intval');
        $this->search['time_type'] = input("time_type");

        $this->assign("is_ban", $this->is_ban);
        $this->assign("search", $this->search);
        $DividendRoleModel = new DividendRoleModel();
        $this->roleList = $DividendRoleModel->getRows();
        $this->assign("roleList", $this->roleList);

        $where[] = ' is_ban = ' . $this->is_ban;
        $reportrange = input('reportrange');
        $search['start_time'] = input('start_time', '', 'trim');
        $search['end_time'] = input('end_time', '', 'trim');
        if (empty($search['start_time']) == false) {
            $dtime[0] = str_replace('_', '-', $search['start_time']);
            $dtime[1] = str_replace('_', '-', $search['end_time']);
        } elseif (empty($reportrange) == false) {
            $dtime = explode('-', $reportrange);
        }
        if (empty($dtime) == false) {
            $dtime[0] = strtotime($dtime[0]);
            $dtime[1] = strtotime($dtime[1]) + 86399;
        }
        switch ($this->search['time_type']) {
            case 'reg_time':
                $where[] = ' u.reg_time between ' . $dtime[0] . ' AND ' . $dtime[1];
                break;
            case 'login_time':
                $where[] = ' u.login_time between ' . $dtime[0] . ' AND ' . $dtime[1];
                break;
            case 'buy_time':
                $where[] = ' u.last_buy_time between ' . $dtime[0] . ' AND ' . $dtime[1];
                break;
            default:
                break;
        }

        if ($this->search['additional_setapply'] > 0) {
            $where[] = ' u.additional_setapply = ' . $this->search['additional_setapply'] * 1;
        }

        if ($this->search['roleId'] == 'all_role') {
            $where[] = ' u.role_id > 0 ';
        } elseif ($this->search['roleId'] >= 0) {
            $where[] = ' u.role_id = ' . $this->search['roleId'] * 1;
        }

        if (empty($this->search['keyword']) == false) {
            if (is_numeric($this->search['keyword'])) {
                $where[] = " ( u.user_id = '" . ($this->search['keyword']) . "' or mobile like '" . $this->search['keyword'] . "%' )";
            } else {
                $where[] = " ( u.user_name like '" . $this->search['keyword'] . "%' or u.nick_name like '" . $this->search['keyword'] . "%' )";
            }
        }
        $export = input('export', 0, 'intval');
        if ($export > 0) {
            return $this->exportList($where);
        }
        $sort_by = input("sort_by", 'DESC', 'trim');
        $order_by = 'u.user_id';
        $viewObj = $this->Model
            ->alias('u')
            ->join("users_account uc", 'u.user_id=uc.user_id', 'left')
            ->where(join(' AND ', $where))->field('u.*,uc.balance_money,uc.use_integral,uc.total_integral,uc.integral_money')->order($order_by . ' ' . $sort_by);

        $data = $this->getPageList($this->Model, $viewObj);

        foreach ($data['list'] as $key => $value) {
            $data['list'][$key]['profit_pid'] = $this->getProfit($value['profit_pid']);
        }

        $levelList = (new UsersLevelApplyModel)->getRows();
        $data['order_by'] = $order_by;
        $data['sort_by'] = $sort_by;
        $this->assign("data", $data);
        $this->assign("levelList", $levelList);
        $this->assign("search", $this->search);
        if ($runData == false) {
            $data['content'] = $this->fetch('sys_admin/users/list')->getContent();
            return $this->success('', '', $data);
        }
        return true;
    }

    /**
     * 获取所属上级 getProfit
     * @param int $pid [上级id]
     * @return void
     */
    public function getProfit($pid = 0)
    {
        $profituser = $this->Model->where('user_id', $pid)->field('role_id,profit_pid,user_id')->find();
        if ($profituser['role_id'] <= 1) {
            if ($profituser['profit_pid'] == 0) {
                return 0;
            }
            return $this->getProfit($profituser['profit_pid']);
        }
        return $profituser['user_id'];
    }
    /*------------------------------------------------------ */
    //-- 导出会员
    /*------------------------------------------------------ */
    public function exportList($where)
    {

        $count = $this->Model->alias('u')->join("users_account uc", 'u.user_id=uc.user_id', 'left')->where(join(' AND ', $where))->field('u.*,uc.balance_money,uc.use_integral,uc.total_integral')->order('u.user_id DESC')->count('u.user_id');

        if ($count < 1) return $this->error('没有找到可导出的日志资料！');
        $filename = '会员列表资料_' . date("YmdHis") . '.xls';
        $export_arr['UID'] = 'user_id';
        $export_arr['注册手机'] = 'mobile';
        $export_arr['昵称'] = 'nick_name';
        $export_arr['推荐人'] = 'pid';
//        $export_arr['等级/身份'] = 'userLevel';
        $export_arr['帐户积分'] = 'balance_money';
        $export_arr['最近登陆'] = 'login_time';

        $export_field = $export_arr;
        $page = 0;
        $page_size = 500;
        $page_count = 100;

        $title = join("\t", array_keys($export_arr)) . "\t";
        unset($export_field['操作用户名']);
        $field = join(",", $export_field);

        $DividendRoleModel = new DividendRoleModel();
        $roleList = $DividendRoleModel->getRows();
        $data = '';
        do {
            $rows = $this->Model->alias('u')->join("users_account uc", 'u.user_id=uc.user_id', 'left')->where(join(' AND ', $where))->field('u.*,uc.balance_money,uc.use_integral,uc.total_integral')->order('u.user_id DESC')->limit($page * $page_size, $page_size)->select();

            if (empty($rows)) return;
            foreach ($rows as $row) {
                foreach ($export_arr as $val) {
                    if (strstr($val, '_time')) {
                        $data .= dateTpl($row[$val]) . "\t";
                    } elseif ($val == 'pid') {

                        if ($row[$val] > 0) {
                            $data .= $row[$val] . '-' . userInfo($row[$val]) . "\t";
                        } else {
                            $data .= '没有上级' . "\t";
                        }

                    } elseif ($val == 'userLevel') {
                        $rode_name = $row['role_id'] == 0 ? '粉丝' : $roleList[$row['role_id']]['role_name'];
                        $data .= userLevel($row['total_integral']) . '/' . $rode_name . "\t";
                    } else {
                        $data .= str_replace(array("\r\n", "\n", "\r"), '', strip_tags($row[$val])) . "\t";
                    }
                }
                $data .= "\n";
            }

            $page++;
        } while ($page <= $page_count);

        $filename = iconv('utf-8', 'GBK//IGNORE', $filename);
        header("Content-type: application/vnd.ms-excel; charset=utf-8");
        header("Content-Disposition: attachment; filename=$filename");
        echo iconv('utf-8', 'GBK//IGNORE', $title . "\n" . $data) . "\t";
        exit;
    }
    /*------------------------------------------------------ */
    //-- 重置密码
    /*------------------------------------------------------ */
    public function restPassword()
    {
        $user_id = input("user_id/d");
        if ($user_id < 0) {
            return $this->error('获取用户ID传值失败！');
        }
        $data['password'] = f_hash('Abc123456');
        $oldpassword = $this->Model->where('user_id', $user_id)->value('password');
        if ($data['password'] == $oldpassword) {
            return $this->error('当前用户密码为系统默认：Abc123456，无须修改.');
        }
        $res = $this->Model->where('user_id', $user_id)->update($data);
        if ($res < 1) {
            return $this->error('未知错误，处理失败.');
        }
        $this->_log($user_id, '重置用户密码.', 'member');
        return $this->success('操作成功.');
    }
    /*------------------------------------------------------ */
    //-- 重置支付密码
    /*------------------------------------------------------ */
    public function restPayPassword()
    {
        $user_id = input("user_id/d");
        if ($user_id < 0) {
            return $this->error('获取用户ID传值失败！');
        }
        $pay_password = rand(100000, 999999);
        $data['pay_password'] = f_hash($pay_password);
        $res = $this->Model->where('user_id', $user_id)->update($data);
        if ($res < 1) {
            return $this->error('未知错误，处理失败.');
        }
        $this->_log($user_id, '重置用户支付密码.', 'member');
        return $this->success('操作成功,新支付密码：' . $pay_password, '', ['alert' => 1]);
    }
    /*------------------------------------------------------ */
    //-- 会员管理
    /*------------------------------------------------------ */
    public function info()
    {
        $user_id = input('user_id/d');
        if ($user_id < 1) return $this->error('获取用户ID传值失败！');
        $row = $this->Model->info($user_id);
        if (empty($row)) return $this->error('用户不存在！');
        $row['wx'] = (new WeiXinUsersModel)->where('user_id', $user_id)->find();
        $this->assign("userShareStats", $this->Model->userShareStats($user_id));
        $row['user_address'] = (new UserAddressModel)->where('user_id', $user_id)->select();
        $row['ld_grade_name'] = $this->ld_grade_name_list($row['ld_grade']);
        $this->assign('row', $row);
        $this->assign('d_level', config('config.dividend_level'));
        $DividendRoleModel = new DividendRoleModel();
        $this->assign("roleList", $DividendRoleModel->getRows());
        $this->assign("teamCount", $this->Model->teamCount($user_id));
        $where[] = ['dividend_uid', '=', $user_id];
        $where[] = ['status', 'in', [2, 3]];
        $DividendModel = new DividendModel();
        $dividend_amount = $DividendModel->where($where)->sum('dividend_amount');
        $this->assign("wait_money", $dividend_amount);
        $has_order = 0;
        //判断订单模块是否存在
        if (class_exists('app\shop\model\OrderModel')) {
            $has_order = 1;
            $this->assign("start_date", date('Y/m/01', strtotime("-1 months")));
            $this->assign("end_date", date('Y/m/d'));
        }
        $this->assign('has_order', $has_order);
        $UsersLevelAgentModel = new UsersLevelAgentModel();
        $users_level_agent = $UsersLevelAgentModel->getRows($user_id);
        $this->assign("users_level_agent", $users_level_agent);
        $UsersLevelModel = new UsersLevelModel();
        $this->levelList = $UsersLevelModel->getRows();
        $this->assign("levelList", $this->levelList);

        $row = $this->Model->info($user_id);
        $all = UsersLevelApplyModel::select();
        $additional_setapply = $row['additional_setapply'];
        $isinsall = explode(",",$additional_setapply);
        $this->assign("isinsall", $isinsall);
        $this->assign("all", $all);

        return $this->fetch('sys_admin/users/info');
    }

    /**
     * [editLevel 修改代理身份]
     * @return [type]        [description]
     */
    public function editLevel()
    {
        $user_id = input('user_id', 0, 'intval');
        $level_id = input('level_id', 0, 'intval');
        $UsersLevelModel = new UsersLevelModel();
        $levelInfo = $UsersLevelModel->getRows()[$level_id];

        //dump($levelInfo);
        if ($this->request->isPost()) {
            $province = input('province', 0, 'intval');
            $city = input('city', 0, 'intval');
            $street = input('street', 0, 'intval');
            $district = input('district', 0, 'intval');
            if (empty($province)) return $this->error('请选择省份');


            $regionInfo = array();

            $awhere[] = ['province', '=', $province];
            $awhere[] = ['level_id', '=', $levelInfo['level_id']];
            $errorText = '该省份已有代理';


            if ($levelInfo['identification'] == 'street_agent') {

                if (empty($street)) return $this->error('请选择街道');
                //$regionInfo = (new \app\mainadmin\model\RegionModel)->info($street);  //原来的区域表
                //start琳凯
                $regionInfo = (new \app\mainadmin\model\AreasModel)->info($street);
                //end琳凯
                $awhere[] = ['district', '=', $district];
                $awhere[] = ['city', '=', $city];
                $awhere[] = ['street', '=', $street];
                $merger_name = $this->getAreasallname($street);
                $errorText = '该街道/乡镇已有代理';
            } elseif ($levelInfo['identification'] == 'district_agent') {
                if (empty($district)) return $this->error('请选择区域');
                //$regionInfo = (new \app\mainadmin\model\RegionModel)->info($district);  //原来的区域表
                //start琳凯
                $regionInfo = (new \app\mainadmin\model\AreasModel)->info($district);
                //end琳凯
                $awhere[] = ['district', '=', $district];
                $awhere[] = ['city', '=', $city];
                $merger_name = $this->getAreasallname($district);
                $errorText = '该区域已有代理';
            } elseif ($levelInfo['identification'] == 'city_agent') {
                if (empty($city)) return $this->error('请选择城市');
                //$regionInfo = (new \app\mainadmin\model\RegionModel)->info($city);  //原来的区域表
                //start琳凯
                $regionInfo = (new \app\mainadmin\model\AreasModel)->info($city);
                //end琳凯
                $awhere[] = ['city', '=', $city];
                $merger_name = $this->getAreasallname($city);
                $errorText = '该城市已有代理';
            } else {
                //$regionInfo = (new \app\mainadmin\model\RegionModel)->info($province);   //原来的区域表
                //琳凯
                $regionInfo = (new \app\mainadmin\model\AreasModel)->info($province);
                //end琳凯
                $merger_name = $this->getAreasallname($province);
            }
            $UsersLevelAgentModel = new UsersLevelAgentModel();
            $count = $UsersLevelAgentModel->lock(true)->where($awhere)->count();
            if ($count > 0) return $this->error($errorText);

            $userInfo = $this->Model->where('user_id', $user_id)->lock(true)->find();

            $inArr['province'] = $province;
            $inArr['city'] = $city;
            $inArr['district'] = $district;
            $inArr['street'] = $street;
            $inArr['level_id'] = $levelInfo['level_id'];
            $inArr['user_id'] = $userInfo['user_id'];
// dump($inArr);
            //$inArr['merger_name'] = $regionInfo['merger_name'];
            $inArr['merger_name'] = $merger_name;

            Db::startTrans();
            if (empty($userInfo[$levelInfo['identification']])) {
                //$userModel = new UsersModel();
                $res = $this->Model->where('user_id', $userInfo['user_id'])->update([$levelInfo['identification'] => $levelInfo['level_id']]);
                if ($res < 1) {
                    Db::rollback();
                    return $this->error('添加失败');
                }
                $this->Model->cleanMemcache($userInfo['user_id']);
            }
            $res = $UsersLevelAgentModel->allowField(true)->save($inArr);

            if ($res < 1) {
                Db::rollback();
                if ($res < 1) return $this->error('添加失败');
            }
            $UsersLevelAgentModel->cleanMemcache($userInfo['user_id']);
            Db::commit();
            $log = '添加【' . $levelInfo['level_name'] . '】代理区域【' . $inArr['merger_name'] . '】';
            $this->_log($userInfo['user_id'], $log, 'member');
            return $this->success('添加成功', 'reload');
        }
        $this->assign("levelInfo", $levelInfo);
        $this->assign("user_id", $user_id);
        return $this->fetch('sys_admin/users/edit_level');
    }

    /*
     *
     * 获取地址全名
     */
    public function getAreasallname($id){

        if(empty($id)){
            return '无';
        }
        //$areasObj = new Areas();
        $areasRes = Db::table('t_areas')->where('id',$id)->find();
        $type = $areasRes['type'];
        if($type == 1){
            return $areasRes['name'];
        }else if($type == 2){
            $pidRes = Db::table('t_areas')->where('id',$areasRes['pid'])->find();
            return $pidRes['name'].','.$areasRes['name'];
        }else if($type == 3){
            $pidRes = Db::table('t_areas')->where('id',$areasRes['pid'])->find();
            $pidpidRes = Db::table('t_areas')->where('id',$pidRes['pid'])->find();
            return $pidpidRes['name'].','.$pidRes['name'].','.$areasRes['name'];
        }else if($type == 4){
            $pidRes = Db::table('t_areas')->where('id',$areasRes['pid'])->find();
            $pidpidRes = Db::table('t_areas')->where('id',$pidRes['pid'])->find();
            $pidpidpidRes = Db::table('t_areas')->where('id',$pidpidRes['pid'])->find();
            return $pidpidpidRes['name'].','.$pidpidRes['name'].','.$pidRes['name'].','.$areasRes['name'];
        }

    }

    /**
     * [delLevel 删除区域]
     * @return [type] [description]
     */
    public function delLevel()
    {
        $user_id = input('user_id', 0, 'intval');
        $id = input('id', 0, 'intval');
        $level_id = input('level_id', 0, 'intval');
        $UsersLevelAgentModel = new UsersLevelAgentModel();
        $AgentInfo = $UsersLevelAgentModel->where('id', $id)->find();

        Db::startTrans();
        $res = $UsersLevelAgentModel->where('id', $id)->delete();
        if ($res < 1) {
            Db::rollback();
            return $this->error('删除失败');
        }
        $UsersLevelAgentModel->cleanMemcache($user_id);
        $where[] = ['user_id', '=', $user_id];
        $where[] = ['level_id', '=', $level_id];
        $count = $UsersLevelAgentModel->where($where)->count();
        if ($count <= 0) {
            $UsersLevelModel = new UsersLevelModel();
            $levelInfo = $UsersLevelModel->getRows()[$level_id];
            $res = $this->Model->where('user_id', $user_id)->update([$levelInfo['identification'] => 0]);
            if ($res < 1) {
                Db::rollback();
                return $this->error('删除失败');
            }
            $this->Model->cleanMemcache($user_id);
        }
        Db::commit();
        $log = '删除【' . $levelInfo['level_name'] . '】代理区域【' . $AgentInfo['merger_name'] . '】';

        $this->_log($user_id, $log, 'member');

        return $this->success('删除成功', 'reload');
    }
    /*------------------------------------------------------ */
    //-- 设置附加分红
    /*------------------------------------------------------ */
    public function setAdditional()
    {
        $user_id = input('user_id', 0, 'intval');
        $row = $this->Model->info($user_id);
        $all = UsersLevelApplyModel::select();
        if ($this->request->isPost()) {
            $data['additional_div'] = json_encode(input('additional_div'));
            $res = $this->Model->upInfo($user_id, $data);
            if ($res < 1) return $this->error('操作失败,请重试.');
            $info = "修改附加分红";
            $this->_log($user_id, $info, 'member');
            return $this->success('修改成功！', 'reload');
        }
        $this->assign("all", $all);
        $this->assign("row", $row);
        $this->assign("additional_div", json_decode($row['additional_div'], true));

        return $this->fetch('sys_admin/users/set_additional');
    }

    /*------------------------------------------------------ */
    //-- 设置解冻扶持基金
    /*------------------------------------------------------ */
    public function setRelease()
    {
        $user_id = input('user_id', 0, 'intval');
        $row = $this->Model->info($user_id);
        if ($this->request->isPost()) {
            $data['isrelease'] = input('isrelease');
            $res = $this->Model->upInfo($user_id, $data);
            if ($res < 1) return $this->error('操作失败,请重试.');
            $info = "设置解冻扶持基金";
            $this->_log($user_id, $info, 'member');
            return $this->success('修改成功！', 'reload');
        }
        $this->assign("row", $row);

        return $this->fetch('sys_admin/users/set_release');
    }

    /*------------------------------------------------------ */
    //-- 设置股东分红池
    /*------------------------------------------------------ */
    public function setAddlevelapply()
    {

        $user_id = input('user_id', 0, 'intval');
        $row = $this->Model->info($user_id);
        $all = UsersLevelApplyModel::select();
        $level_id = input('level_id','',array());
        if($level_id){
            $level_idstr = '';
            foreach ($level_id as $k=>$v) {
                $level_idstr .= $v.',';
            }
        }
        $level_idstr = rtrim($level_idstr,',');

        //dump($level_idstr);
        if ($this->request->isPost()) {
            $data['additional_setapply'] = $level_idstr;
            $data['additional_div'] = json_encode(input('additional_div'));
            $res = $this->Model->upInfo($user_id, $data);
            if ($res < 1) return $this->error('操作失败,请重试.');
            $info = "设置股东分红池";
            $this->_log($user_id, $info, 'member');
            return $this->success('修改成功！', 'reload');
        }

        $additional_setapply = $row['additional_setapply'];
        $isinsall = explode(",",$additional_setapply);

        $this->assign("isinsall", $isinsall);
        $this->assign("all", $all);
        $this->assign("row", $row);
        $this->assign("additional_setapply", json_decode($row['additional_setapply'], true));
        $this->assign("additional_div", json_decode($row['additional_div'], true));

        return $this->fetch('sys_admin/users/set_addlevelapply');
    }

    public function isHave(){
        return 0;
    }

    /*------------------------------------------------------ */
    //-- 修改分销身份
    /*------------------------------------------------------ */
    public function editRole()
    {
        $user_id = input('user_id', 0, 'intval');
        $row = $this->Model->info($user_id);
        $DividendRoleModel = new DividendRoleModel();
        $roleList = $DividendRoleModel->getRows();
        if ($this->request->isPost()) {
            $data['role_id'] = input('role_id', 0, 'intval');
            $this->checkUpData($row, $data);
            $data['last_up_role_time'] = time();
            if($data['role_id'] == 1 || ($data['role_id'] == 2 && $row['role_id'] == 0)){
                $data['up_agent_time'] = time();
            }
            $res = $this->Model->upInfo($user_id, $data);
            if ($res < 1) return $this->error('操作失败,请重试.');
            $info = '后台手工操作由【' . ($row['role_id'] == 0 ? '粉丝' : $roleList[$row['role_id']]['role_name']) . '】调整为【' . ($data['role_id'] < 1 ? '粉丝' : $roleList[$data['role_id']]['role_name']) . '】';
            $this->_log($user_id, $info, 'member');
            return $this->success('修改分佣身份成功！', 'reload');
        }
        $this->assign("roleList", $roleList);
        $this->assign("row", $row);

        return $this->fetch('sys_admin/users/edit_role');
    }

        public function editDz()
    {
        $user_id = input('user_id', 0, 'intval');
        $row = $this->Model->info($user_id);
        if ($this->request->isPost()) {
            $data['is_dz'] = input('is_dz', 0, 'intval');
//            $this->checkUpData($row, $data);
//            $data['last_up_role_time'] = time();
            $res = $this->Model->upInfo($user_id, $data);
            if ($res < 1) return $this->error('操作失败,请重试.');
            $info = '后台手工操作由【' . ($row['is_dz'] == 0 ? '不是导师' :'是导师' ) . '】调整为【' . ($data['is_dz'] == 1 ? '是导师' :'不是导师') . '】';
            $this->_log($user_id, $info, 'member');
            return $this->success('修改导师身份成功！', 'reload');
        }
        $this->assign("row", $row);

        return $this->fetch('sys_admin/users/edit_dz');
    }
    /*------------------------------------------------------ */
    //-- 封禁会员
    /*------------------------------------------------------ */
    public function evelBan()
    {
        $user_id = input('user_id', 0, 'intval');
        $row = $this->Model->info($user_id);
        if ($row['is_ban'] == 1) return $this->error('会员已被封禁，无须重复操作.');
        $data['is_ban'] = 1;
        $res = $this->Model->upInfo($user_id, $data);
        if ($res < 1) return $this->error();
        $this->_log($user_id, '后台封禁会员.', 'member');
        return $this->success('禁封成功.', 'reload');
    }
    /*------------------------------------------------------ */
    //-- 解禁会员
    /*------------------------------------------------------ */
    public function reBan()
    {
        $user_id = input('user_id', 0, 'intval');
        $row = $this->Model->info($user_id);
        if ($row['is_ban'] == 0) return $this->error('会员已被解禁，无须重复操作.');
        $data['is_ban'] = 0;
        $res = $this->Model->upInfo($user_id, $data);
        if ($res < 1) return $this->error('操作失败,请重试.');
        $this->_log($user_id, '后台解禁会员.', 'member');
        return $this->success('解禁成功.', 'reload');
    }
    /*------------------------------------------------------ */
    //-- 根据关键字查询
    /*------------------------------------------------------ */
    public function pubSearch()
    {
        $keyword = input('keyword', '', 'trim');
        $user_level = input('user_level', '', 'trim');

        $where = "user_id > 0";
        if (!empty($keyword)) {
            $where .= " AND  ( mobile LIKE '%" . $keyword . "%' OR user_id = '" . $keyword . "' OR nick_name LIKE '%" . $keyword . "%' OR mobile LIKE '%" . $keyword . "%')";
        }
        if ($user_level > 0) {
            $level = $this->levelList[$this->search['levelId']];
            $where .= ' AND total_integral between ' . $level['min'] . ' AND ' . $level['max'];
        }
        $_list = $this->Model->where($where)->field("user_id,mobile,nick_name,user_name")->limit(20)->select();
        foreach ($_list as $key => $row) {
            $_list[$key] = $row;
        }
        $result['list'] = $_list;
        $result['code'] = 1;
        return $this->ajaxReturn($result);
    }
    /*------------------------------------------------------ */
    //-- 下级名单
    /*------------------------------------------------------ */
    public function getChainList()
    {
        $user_id = input('user_id', 0, 'intval');
        if ($user_id < 1) {
            $result['list'] = [];
            return $this->ajaxReturn($result);
        }
        $DividendRole = (new DividendRoleModel)->getRows();
        $rows = $this->Model->field('user_id,nick_name,role_id')->where('pid', $user_id)->select();
        foreach ($rows as $key => $row) {
            $row['role_name'] = $DividendRole[$row['role_id']]['role_name'];
            $row['teamCount'] = $this->Model->teamCount($row['user_id']) + 1;
            $rows[$key] = $row;
        }
        $result['list'] = $rows;
        return $this->ajaxReturn($result);
    }
    /*------------------------------------------------------ */
    //-- 上级名单
    /*------------------------------------------------------ */
    public function getSuperiorList()
    {
        $user_id = input('user_id', 0, 'intval');
        $result['code'] = 1;
        $result['list'] = $this->Model->getSuperiorList($user_id);
        return $this->ajaxReturn($result);
    }

    /*------------------------------------------------------ */
    //-- 执行统计
    /*------------------------------------------------------ */
    public function evalStat()
    {
        $reportrange = input('reportrange', '2019/01/01 - 2019/03/21', 'trim');
        $user_id = input('user_id', '0', 'intval');

        $dtime = explode('-', $reportrange);
        $UsersBindSuperiorModel = new UsersBindSuperiorModel();
        $where[] = ['', 'exp', Db::raw("FIND_IN_SET('" . $user_id . "',superior)")];
        $user_ids = $UsersBindSuperiorModel->where($where)->column('user_id');

        $oWhere[] = ['o.user_id', 'in', $user_ids];
        $oWhere[] = ['o.order_status', '=', 1];
        $oWhere[] = ['o.add_time', 'between', [strtotime($dtime[0]), strtotime($dtime[1]) + 86399]];
        $viewObj = (new \app\shop\model\OrderModel)->alias('o')->field('o.user_id,o.order_id,o.user_id,o.order_amount,o.dividend_amount,og.goods_name,og.goods_id,og.goods_name,og.goods_number,og.shop_price,og.sale_price');
        $viewObj->join("shop_order_goods og", 'og.order_id=o.order_id', 'left');
        $rows = $viewObj->where($oWhere)->select()->toArray();
        $result['buyGoods'] = [];
        $nowUser = [];

        $order_ids = $user_order_ids = [];
        $buy_ser_ids = [];
        $team_amount = [];
        $user_amount = [];
        foreach ($rows as $row) {
            if ($row['goods_id'] < 1) continue;
            $order_ids[$row['order_id']] = 1;
            $buy_ser_ids[$row['user_id']] = 1;
            $result['buyGoods'][$row['goods_id']]['goods_name'] = $row['goods_name'];
            $result['buyGoods'][$row['goods_id']]['num'] += $row['goods_number'];
            $result['buyGoods'][$row['goods_id']]['price'] += ($row['sale_price'] * $row['goods_number']);
            $team_amount[$row['order_id']]['dividend_amount'] = $row['dividend_amount'];
            $team_amount[$row['order_id']]['order_amount'] = $row['order_amount'];
            if ($row['user_id'] == $user_id) {
                $nowUser['buyGoods'][$row['goods_id']]['goods_name'] = $row['goods_name'];
                $nowUser['buyGoods'][$row['goods_id']]['num'] += $row['goods_number'];
                $nowUser['buyGoods'][$row['goods_id']]['price'] += ($row['sale_price'] * $row['goods_number']);
                $user_order_ids[$row['order_id']] = 1;
                $user_amount[$row['order_id']]['dividend_amount'] = $row['dividend_amount'];
                $user_amount[$row['order_id']]['order_amount'] = $row['order_amount'];
            }
        }

        $result['dividend_amount'] = 0;
        $result['order_amount'] = 0;
        foreach ($team_amount as $tarr) {
            $result['dividend_amount'] += $tarr['dividend_amount'];
            $result['order_amount'] += $tarr['order_amount'];
        }
        $nowUser['dividend_amount'] = 0;
        $nowUser['order_amount'] = 0;
        foreach ($user_amount as $uarr) {
            $nowUser['dividend_amount'] += $uarr['dividend_amount'];
            $nowUser['order_amount'] += $uarr['order_amount'];
        }

        $result['code'] = 1;
        $result['reportrange'] = $reportrange;
        $result['order_num'] = count($order_ids);
        $result['buy_user_num'] = count($buy_ser_ids);
        $nowUser['order_num'] = count($user_order_ids);
        $result['nowUser'] = $nowUser;
        return $this->ajaxReturn($result);
    }
    /*------------------------------------------------------ */
    //-- 修改所属上级
    /*------------------------------------------------------ */
    public function editSuperior()
    {
        $user_id = input('user_id', 0, 'intval');
        $userInfo = $this->Model->info($user_id);
        if ($this->request->isPost()) {
            $mkey = 'evaleditSuperior';
            $cache = Cache::get($mkey);
            if (empty($cache) == false) {
                return $this->error('当前正在有人操作调整，请稍后再操作.');
            }
            Cache::get($mkey, true, 60);
            $setTopUser = input('setTopUser', 0, 'intval');
            if ($setTopUser == 1) {
                $select_user_id = 0;
            } else {
                $select_user_id = input('select_user', 0, 'intval');
                if ($select_user_id < 1) {
                    return $this->error('请选择需要修改的上级.');
                }
                if ($select_user_id == $userInfo['pid']) {
                    return $this->error('当前选择与当前会员上级一致，请核实.');
                }
                if ($select_user_id == $userInfo['user_id']) {
                    return $this->error('不能选择自己作为自己的上级.');
                }
                $where[] = ['', 'exp', Db::raw("FIND_IN_SET('" . $user_id . "',superior)")];
                $where[] = ['user_id', '=', $select_user_id];
                $count = (new UsersBindSuperiorModel)->where($where)->count();
                if ($count > 0) {
                    return $this->error('不能选择自己的下级作为上级.');
                }
            }
            Db::startTrans();//启动事务
            $res = $this->Model->upInfo($user_id,['ld_agnetid'=>$select_user_id,'pid'=>$select_user_id, 'profit_pid'=> $select_user_id]);

            if ($res < 1){
                Db::rollback();
                return $this->error('修改会员所属上级失败.');
            }

            //会员上级汇总处理end
            $res = $this->Model->regUserBind($user_id, $select_user_id, true);//重新绑定当前用户的关系链
            if ($res == false) {
                Db::rollback();
                return $this->error('绑定当前会员关系链失败.');
            }
            Db::commit();//事务，提交
            Cache::rm($mkey);
            $this->_log($user_id, '调整会员所属上级，原所属上级ID：' . $userInfo['pid'], 'member');
            return $this->success('修改所属上级成功！', 'reload');
        }
        if ($userInfo['pid'] > 0) {
            $userInfo['puser'] = $this->Model->info($userInfo['pid']);
        }
        $this->assign("row", $userInfo);
        return $this->fetch('sys_admin/users/edit_superior');
    }

    public function editAllPid()
    {
        $res = $this->Model->where('pid', '>', 0)->select()->toArray();
        foreach ($res as $uses) {
            //会员上级汇总处理end
            $res = $this->Model->upInfo($uses['user_id'], ['pid' => 0, 'profit_pid' => 0]);
            $res = $this->Model->regUserBind($uses['user_id'], 0, true);//重新绑定当前用户的关系链
        }
    }


    /*------------------------------------------------------ */
    //-- 搜索会员
    /*------------------------------------------------------ */
    public function searchBox()
    {
        $this->assign('rode_id', input('rode_id', 0, 'intval'));
        $this->assign("start_date", date('Y/m/01', strtotime("-1 months")));
        $this->assign("end_date", date('Y/m/d'));
        $this->getList(true);

        //首页跳转时间
        $start_date = input('start_time', '0', 'trim');
        $end_date = input('end_time', '0', 'trim');
        if ($start_date || $end_date) {

            $this->assign("start_date", str_replace('_', '/', $start_date));
            $this->assign("end_date", str_replace('_', '/', $end_date));
        }

        return $this->fetch('sys_admin/users/search_box');
    }

    /*------------------------------------------------------ */
    //-- 搜索会员
    /*------------------------------------------------------ */
    public function getSearchList()
    {
        $this->getList(true);
        $this->data['content'] = $this->fetch('sys_admin/users/search_list')->getContent();
        return $this->success('', '', $this->data);
    }

    /*------------------------------------------------------ */
    //-- 新增会员
    /*------------------------------------------------------ */
    public function addUser()
    {
        if ($this->request->isPost()) {
            $inArr = input('post.');
            if (!$inArr['password'] || !$inArr['password_again']) {
                return $this->error('请输入密码');
            }
            if ($inArr['password'] != $inArr['password_again']) {
                return $this->error('两次密码不一致，请重新输入');
            }
            unset($inArr['password_again']);
            session('share_token', '');
            $res = $this->Model->register($inArr, 0, true, $this);
            if ($res === true) {
                return $this->success('添加成功.');
            }
            return $this->error($res);
        }
        return $this->fetch();
    }
    /*------------------------------------------------------ */
    //-- 修改手机号码
    /*------------------------------------------------------ */
    public function upMobile()
    {
        $user_id = input('user_id');
        $user = $this->Model->find($user_id);
        if (empty($user)) {
            return $this->error('用户不存在.');
        }
        if ($this->request->isPost()) {
            $mobile = input('mobile');
            if (checkMobile($mobile) == false) {
                // return '手机号码不正确.';
                return $this->error('手机号码不正确');
            }
            $count = $this->Model->where('mobile', $mobile)->count('user_id');
            if ($count > 0) {
                return $this->error('手机号已存在');
            }
            $upDate['mobile'] = $mobile;
            $res = $this->Model->where('user_id', $user_id)->update($upDate);
            if ($res < 1) {
                return $this->error('未知错误，处理失败.');
            }
            $this->Model->cleanMemcache($user_id);
            $text = '原手机号:' . $user['mobile'] . '改为' . $mobile;
            $this->_log($user_id, $text);
            return $this->success('修改成功.');
        }
        $this->assign('user', $user);
        return $this->fetch('sys_admin/users/up_mobile');
    }
    /*------------------------------------------------------ */
    //-- 获取用户操作日志
    /*------------------------------------------------------ */
    public function getOptLogList()
    {
        $user_id = input('user_id', 0, 'intval');
        if ($user_id < 1) {
            return $this->error('代理ID不能为空');
        }
        $logs = (new LogSysModel)->where('edit_id', $user_id)->order('log_id DESC')->select()->toArray();
        foreach ($logs as $key => $log) {
            $log['admin_info'] = $log['user_id'] . '-' . adminInfo($log['user_id']);
            $log['log_time'] = dateTpl($log['log_time']);
            $logs[$key] = $log;
        }
        $data['list'] = $logs;
        return $this->success('ok', '', $data);
    }
}
